//
//  AppDelegate.m
//  TEST
//
//  Created by huajun on 2017/6/20.
//  Copyright © 2017年 huajun. All rights reserved.
//

#import "AppDelegate.h"
#import <UserNotifications/UserNotifications.h>
#import "JPUSHService.h"

#define kDeviceVersion [[UIDevice currentDevice].systemVersion floatValue]

@interface AppDelegate ()<UNUserNotificationCenterDelegate,JPUSHRegisterDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    //注册远程通知服务
    [self replyPushNotificationAuthorization];
    
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 可以添加自定义categories
        // NSSet<UNNotificationCategory *> *categories for iOS10 or later
        // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
    }
    
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    [JPUSHService setupWithOption:launchOptions appKey:@"71e723db8f111f42858bd770"
                          channel:@"App Store"
                 apsForProduction:NO
            advertisingIdentifier:nil];
  
    
    return YES;
}

- (void)replyPushNotificationAuthorization {
    
    if (kDeviceVersion >= 10.0) {
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        center.delegate = self;
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge|UNAuthorizationOptionSound|UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (!error && granted) {
                NSLog(@"[IOS10远程通知服务注册成功]");
            }
            else {
                NSLog(@"[IOS10远程通知服务注册失败]");
            }
        }];
        [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
            //            NSLog(@"[IOS10远程通知服务用户设置] %@",settings);
        }];
    }
    else if (kDeviceVersion >= 8.0) {
        [[UIApplication sharedApplication]registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeAlert|UIUserNotificationTypeSound|UIUserNotificationTypeBadge) categories:nil]];
    }
    [[UIApplication sharedApplication]registerForRemoteNotifications];
}

#pragma mark IOS10远程通知服务代理一:APP处于前台接收通知时
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
    
    //收到推送的请求
    UNNotificationRequest *request = notification.request;
    //收到推送的内容
    UNNotificationContent *content = request.content;
    //收到用户的基本信息
//    NSDictionary *userInfo = content.userInfo;
    //收到消息的角标
//    NSNumber *badge = content.badge;
    //收到消息的body
    NSString *body = content.body;
    //收到消息的声音
//    UNNotificationSound *sound = content.sound;
    //收到消息的标题
//    NSString *title = content.title;
    //收到消息的副标题
//    NSString *subtitle = content.subtitle;
    
    if ([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        
        
//        NSDictionary *apsDict = userInfo[@"aps"];
        
        if ([body isEqualToString:@"kickoff"]||[body isEqualToString:@"您的帐号已在其他的设备上登录"]) {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"您的帐号已在其他的设备上登录" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            alert.tag = 20;
            [alert show];
        }
       
    }
    else {
        
        
    }
    
    //打开后，APP在前台也会收到推送通知
    completionHandler(UNAuthorizationOptionAlert|UNAuthorizationOptionSound|UNAuthorizationOptionBadge);
}

#pragma mark IOS10远程通知服务代理二：APP通知的点击事件
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    
    //收到推送的请求
    UNNotificationRequest *request = response.notification.request;
    //收到推送的内容
    UNNotificationContent *content = request.content;
    //收到用户的基本信息
    NSDictionary *userInfo = content.userInfo;
    //收到消息的角标
//    NSNumber *badge = content.badge;
    //收到消息的body
    NSString *body = [NSString stringWithFormat:@"%@",content.body];
    //收到消息的声音
//    UNNotificationSound *sound = content.sound;
    //收到消息的标题
//    NSString *title = content.title;
    //收到消息的副标题
//    NSString *subtitle = content.subtitle;
    
    if ([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        
        NSDictionary *apsDict = userInfo[@"aps"];
        
        if ([body isEqualToString:@"kickoff"]||[body isEqualToString:@"您的帐号已在其他的设备上登录"]) {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"您的帐号已在其他的设备上登录" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            alert.tag = 20;
            [alert show];
        }
        else if ([body isEqualToString:@"xinyonghu"]||[body isEqualToString:@"有新用户向您添加好友"]){
            
        }
        else if (apsDict[@"category"] != nil) {
            if ([apsDict[@"category"] isEqualToString:@"message"]) {
                
                
               
            }
            else if ([apsDict[@"category"] rangeOfString:@"http://"].location != NSNotFound || [apsDict[@"category"] rangeOfString:@"https://"].location != NSNotFound) {
                
                
            }
        }
    }
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
//    completionHandler();
}


#pragma mark IOS10之前版本远程通知服务代理:APP接收通知时
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    
    NSDictionary *apsDict = userInfo[@"aps"];
    
    
    if ([apsDict[@"alert"] isEqualToString:@"kickoff"]||[apsDict[@"alert"] isEqualToString:@"您的帐号已在其他的设备上登录"]) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"您的帐号已在其他的设备上登录" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        alert.tag = 20;
        [alert show];
    }
    else if ([apsDict[@"alert"] isEqualToString:@"xinyonghu"]||[apsDict[@"alert"] isEqualToString:@"有新用户向您添加好友"]){
        //刷新通讯录
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"有新用户向您添加好友" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        alert.tag = 10;
        [alert show];
    }
    else if (apsDict[@"category"] != nil) {
        if ([apsDict[@"category"] isEqualToString:@"message"]) {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:apsDict[@"alert"] delegate:self cancelButtonTitle:@"忽略" otherButtonTitles:@"去看看", nil];
            alert.tag = 101;
            [alert show];
        }
        else if ([apsDict[@"category"] rangeOfString:@"http://"].location != NSNotFound || [apsDict[@"category"] rangeOfString:@"https://"].location != NSNotFound) {
            
            
        }
        else {
            
        }
    }
    else {
        
    }
    completionHandler(UIBackgroundFetchResultNewData);
}

#pragma mark 远程通知服务注册成功
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    [JPUSHService registerDeviceToken:deviceToken];
    
    
}

#pragma mark 远程通知服务注册失败
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    
   
    
    
}



- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    // Required,For systems with less than or equal to iOS6
    [JPUSHService handleRemoteNotification:userInfo];
}

//    收到通知
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        NSDictionary *apsDict = userInfo[@"aps"];
        NSString *alert = apsDict[@"alert"];
        NSLog(@"++++++%@",apsDict);
    }
    completionHandler(UNAuthorizationOptionAlert|UNAuthorizationOptionSound|UNAuthorizationOptionBadge); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
}

// iOS 10 Support   点击通知事件
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        NSDictionary *apsDict = userInfo[@"aps"];
        NSLog(@"=======%@",apsDict);
    }
    completionHandler();  // 系统要求执行这个方法
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    [UIApplication sharedApplication].applicationIconBadgeNumber=0;
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
